<template>
  <div class="language-selector">
    <el-select
      v-model="currentLanguage"
      :placeholder="$t('form.languageSelector.selectPlaceholder')"
      size="default"
      @change="handleLanguageChange"
    >
      <template #label="{ label, value }">
        <div class="language-selector-item">
          <el-icon size="18">
            <TablerLanguage />
          </el-icon>
          <span>{{ label }}</span>
        </div>
      </template>
      <el-option
        v-for="lang in languages"
        :key="lang.code"
        :label="lang.name"
        :value="lang.code"
      />
      <template #footer>
        <div
          class="language-settings-btn"
          @click="dialogVisible = true"
        >
          <el-icon size="18">
            <ele-Setting />
          </el-icon>
          <span>{{ $t("form.languageSelector.languageSettings") }}</span>
        </div>
      </template>
    </el-select>

    <el-dialog
      v-model="dialogVisible"
      :title="$t('form.languageSelector.languageSettings')"
      append-to-body
    >
      <el-button
        class="mb10"
        size="default"
        type="success"
        @click="showAddLanguageDialog"
      >
        {{ $t("form.languageSelector.addLanguage") }}
      </el-button>
      <VueDraggable
        v-model="languages"
        :animation="150"
        target="tbody"
      >
        <el-table
          :data="languages"
          style="width: 100%"
        >
          <el-table-column
            prop="name"
            width="180"
          >
            <el-icon size="20">
              <TablerGripHorizontal />
            </el-icon>
          </el-table-column>
          <el-table-column
            :label="$t('form.languageSelector.languageName')"
            prop="name"
            width="180"
          ></el-table-column>
          <el-table-column
            :label="$t('form.languageSelector.isDefaultLanguage')"
            width="180"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.default"
                @change="handleDefaultChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                v-if="!scope.row.default"
                size="small"
                text
                type="success"
                @click="fastTranslationLanguage(scope.row)"
              >
                {{ $t("form.languageSelector.oneClickTranslate") }}
              </el-button>
              <el-button
                size="small"
                text
                type="primary"
                @click="editLanguage(scope.row)"
              >
                {{ $t("form.languageSelector.edit") }}
              </el-button>
              <el-button
                :disabled="languages.length <= 1 || scope.row.default"
                size="small"
                text
                type="danger"
                @click="removeLanguage(scope.row)"
              >
                {{ $t("form.languageSelector.remove") }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </VueDraggable>
      <template #footer>
        <el-button
          size="default"
          @click="dialogVisible = false"
        >
          {{ $t("form.languageSelector.cancel") }}
        </el-button>
        <el-button
          size="default"
          type="primary"
          @click="saveSettings"
        >
          {{ $t("form.languageSelector.save") }}
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="addLanguageDialogVisible"
      :title="$t('form.languageSelector.addSurveyLanguage')"
      append-to-body
      width="450"
    >
      <div
        v-if="availableLanguages.length > 0"
        class="language-grid"
      >
        <div
          v-for="lang in availableLanguages"
          :key="lang.code"
          :class="{ selected: selectedLanguages.includes(lang.code) }"
          class="language-card"
          @click="toggleLanguageSelection(lang)"
        >
          <div class="language-code">{{ lang.code.split("-")[0] }}</div>
          <div class="language-name">{{ lang.name }}</div>
        </div>
      </div>
      <div
        v-else
        class="no-languages-message"
      >
        <el-empty :description="$t('form.languageSelector.noLanguagesAvailable')" />
      </div>
      <template #footer>
        <el-button
          size="default"
          @click="addLanguageDialogVisible = false"
        >
          {{ $t("form.languageSelector.cancel") }}
        </el-button>
        <el-button
          :disabled="selectedLanguages.length === 0"
          size="default"
          type="primary"
          @click="addSelectedLanguages"
        >
          {{ $t("form.languageSelector.add") }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import TablerLanguage from "~icons/tabler/language";
import TablerGripHorizontal from "~icons/tabler/grip-horizontal";
import { computed, onMounted, ref, watch } from "vue";
import { VueDraggable } from "vue-draggable-plus";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { formDesign } from "../hooks/useFormDesign";
import { translateFormContent, updateFormLocaleConfigRequest } from "@/api/project/form";
import { allLanguages, i18nKeyMap } from "@/views/formgen/utils/formI18n";
import { i18n } from "@/i18n";

// 定义语言接口
interface Language {
  name: string;
  code: string;
  default: boolean;
}

// 定义翻译事件返回值接口
interface TranslationResult {
  langCode: string;
  langName: string;
}

const dialogVisible = ref(false);
const addLanguageDialogVisible = ref(false);
const selectedLanguages = ref<string[]>([]);

// 当前已选择的语言
const languages = ref<Language[]>([{ name: "简体中文", code: "zh-CN", default: true }]);

const { localeConfig, formKey, currentLanguage } = formDesign;

// 计算可添加的语言（排除已选择的）
const availableLanguages = computed(() => {
  const currentCodes = languages.value.map(lang => lang.code);
  return allLanguages.filter(lang => !currentCodes.includes(lang.code));
});

// 在组件挂载时加载语言设置
onMounted(async () => {
  await loadLanguageSettings();
});

// 从本地配置加载语言设置
const loadLanguageSettings = async () => {
  try {
    // 从localeConfig.value中获取语言设置
    if (localeConfig.value.langCodes && localeConfig.value.langCodes.length > 0) {
      // 将保存的语言代码转换为完整的语言对象
      languages.value = localeConfig.value.langCodes.map(code => {
        const langInfo = allLanguages.find(lang => lang.code === code) || { name: code, code: code, default: false };

        // 设置默认语言
        langInfo.default = code === localeConfig.value.defaultLang;
        return langInfo;
      });

      // // 设置当前语言为默认语言
      // const defaultLang = languages.value.find(lang => lang.default);
      // if (defaultLang) {
      //   currentLanguage.value = defaultLang.code;
      // } else {
      //   currentLanguage.value = languages.value[0].code;
      // }
    } else {
      languages.value = [{ name: "简体中文", code: "zh-CN", default: true }];
      // currentLanguage.value = "zh-CN";
    }
  } catch (error) {
    console.error("加载语言设置失败:", error);
  }
};

// 监听localeConfig变化，自动重新加载语言设置
watch(
  () => localeConfig.value,
  val => {
    if (val) {
      loadLanguageSettings();
    }
  },
  { deep: true, once: true }
);

const handleLanguageChange = (value: string) => {
  currentLanguage.value = value;
};

const editLanguage = (language: Language) => {
  console.log("编辑语言:", language);
  currentLanguage.value = language.code;
  saveSettings();
};

const removeLanguage = (language: Language) => {
  if (languages.value.length <= 1) {
    return; // 至少保留一种语言
  }

  if (language.default) {
    return; // 不能删除默认语言
  }

  const index = languages.value.findIndex(lang => lang.code === language.code);
  if (index !== -1) {
    languages.value.splice(index, 1);

    // 如果删除的是当前选中的语言，则切换到默认语言
    if (currentLanguage.value === language.name) {
      const defaultLang = languages.value.find(lang => lang.default);
      if (defaultLang) {
        currentLanguage.value = defaultLang.name;
      } else {
        currentLanguage.value = languages.value[0].name;
      }
    }
  }
};

// 处理默认语言切换
const handleDefaultChange = (language: Language) => {
  if (language.default) {
    // 如果当前语言被设为默认，则将其他语言设为非默认
    languages.value.forEach(lang => {
      if (lang.code !== language.code) {
        lang.default = false;
      }
    });
  } else {
    // 如果当前默认语言被取消，确保至少有一个默认语言
    const hasDefault = languages.value.some(lang => lang.default);
    if (!hasDefault && languages.value.length > 0) {
      // 如果没有默认语言，将第一个设为默认
      languages.value[0].default = true;
    }
  }
};

const saveSettings = async () => {
  // 确保只有一个默认语言
  let hasDefault = false;
  for (let i = 0; i < languages.value.length; i++) {
    if (languages.value[i].default) {
      if (hasDefault) {
        languages.value[i].default = false;
      } else {
        hasDefault = true;
      }
    }
  }

  // 如果没有默认语言，将第一个设为默认
  if (!hasDefault && languages.value.length > 0) {
    languages.value[0].default = true;
  }

  try {
    // 获取默认语言代码
    const defaultLang = languages.value.find(lang => lang.default);
    const defaultLangCode = defaultLang ? defaultLang.code : languages.value[0].code;

    // 提取所有语言代码
    const langCodes = languages.value.map(lang => lang.code);

    // 更新localeConfig.value
    localeConfig.value.langCodes = langCodes;
    localeConfig.value.defaultLang = defaultLangCode;

    console.log({
      langCodes: langCodes,
      defaultLang: defaultLangCode
    });
    // 同时调用API保存设置
    await updateFormLocaleConfigRequest({
      formKey: formKey.value,
      localeConfig: {
        langCodes: langCodes,
        defaultLang: defaultLangCode
      }
    });

    // 关闭对话框
    dialogVisible.value = false;

    // 成功提示
    ElMessage({
      type: "success",
      message: i18n.global.t("form.languageSelector.saveSuccess")
    });
  } catch (error) {
    console.error("保存语言设置失败:", error);
    // 错误提示
    ElMessage({
      type: "error",
      message: i18n.global.t("form.languageSelector.saveFailed")
    });
  }
};

const showAddLanguageDialog = () => {
  selectedLanguages.value = [];
  addLanguageDialogVisible.value = true;
};

const toggleLanguageSelection = (lang: Language) => {
  const index = selectedLanguages.value.indexOf(lang.code);
  if (index === -1) {
    selectedLanguages.value.push(lang.code);
  } else {
    selectedLanguages.value.splice(index, 1);
  }
};

const addSelectedLanguages = () => {
  // 将选中的语言添加到languages列表中
  selectedLanguages.value.forEach(code => {
    const langToAdd = allLanguages.find(lang => lang.code === code);
    if (langToAdd) {
      languages.value.push({ ...langToAdd });
    }
  });

  addLanguageDialogVisible.value = false;
};

// 一键翻译功能
const fastTranslationLanguage = async (row: Language) => {
  const defaultLang = languages.value.find(lang => lang.default);
  if (!defaultLang) {
    ElMessage.error(i18n.global.t("form.languageSelector.defaultLanguageNotFound"));
    return;
  }
  let loadingInstance: any = null;
  try {
    await ElMessageBox.confirm(
      i18n.global.t("form.languageSelector.translateConfirm", {
        sourceLang: defaultLang.name,
        targetLang: row.name
      }),
      i18n.global.t("form.languageSelector.confirmTranslate"),
      {
        confirmButtonText: i18n.global.t("form.languageSelector.confirmTranslate"),
        cancelButtonText: i18n.global.t("form.languageSelector.cancel"),
        type: "warning"
      }
    );

    loadingInstance = ElLoading.service({
      text: i18n.global.t("form.languageSelector.translating"),
      background: "rgba(0, 0, 0, 0.7)"
    });

    // 假设formData包含了需要翻译的表单数据
    // 需要根据你的实际数据结构调整
    const params = {
      formKey: formKey.value as string, // 表单ID
      sourceLang: languages.value.find(lang => lang.default)?.code as string, // 源语言，默认中文
      targetLang: row.code, // 目标语言代码
      i18nMappingConfig: i18nKeyMap // 获取需要翻译的内容
    };

    await translateFormContent(params);

    ElMessage.success(i18n.global.t("form.languageSelector.translateSuccess"));

    // 使用 ElMessageBox 询问用户是否查看翻译结果
    ElMessageBox.confirm(
      i18n.global.t("form.languageSelector.translateComplete", {
        sourceLang: defaultLang.name,
        targetLang: row.name
      }),
      i18n.global.t("form.languageSelector.translateSuccess"),
      {
        confirmButtonText: i18n.global.t("form.languageSelector.viewNow"),
        cancelButtonText: i18n.global.t("form.languageSelector.viewLater"),
        type: "success"
      }
    )
      .then(() => {
        // 用户点击"立即查看"按钮
        // 保存当前设置
        saveSettings();

        // 发送事件通知父组件切换到预览模式并使用该语言
        emit("translationSuccess", {
          langCode: row.code,
          langName: row.name
        });
      })
      .catch(() => {
        // 用户点击"稍后查看"按钮，不做任何操作
      });
  } catch (error) {
    if (error === "cancel") return; // 用户取消翻译操作
    console.error("翻译出错:", error);
  } finally {
    loadingInstance?.close();
  }
};

// 定义emit事件类型
const emit = defineEmits<{
  (event: "translationSuccess", payload: TranslationResult): void;
}>();
</script>

<style scoped>
.language-selector {
  width: 166px;
  display: flex;
  gap: 12px;
  position: absolute;
  top: 15px;
  right: 354px;
  padding: 6px 20px;
  z-index: 888;
}

.language-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.language-card {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 16px;
  cursor: pointer;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.language-card:hover {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.language-card.selected {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.language-card.selected::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  border-style: solid;
  border-width: 0 30px 30px 0;
  border-color: transparent var(--el-color-primary) transparent transparent;
}

.language-code {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.language-name {
  font-size: 14px;
  color: #606266;
}

.no-languages-message {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.language-settings-btn {
  padding: 6px;
  font-size: 14px;
  cursor: pointer;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.language-settings-btn:hover {
  background-color: var(--el-color-primary-light-9);
}

.language-selector-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
